package com.enjoy.james.service;

import com.enjoy.james.remoteService.RemoteServiceCall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.*;

@Service
public class JimsOrderService {
	@Autowired
	RemoteServiceCall remoteServiceCall;
	class  Request{
		String orderCode;
		String serialNo;
		CompletableFuture<Map<String, Object>> future;
	}

	LinkedBlockingQueue<Request> queue = new LinkedBlockingQueue<>();

	//线程调用方法
	//线程1－士兵1－－－orderCode
	public Map<String, Object> queryOrderInfo(String orderCode) throws InterruptedException, ExecutionException {
		//orderCode;
		String serialNo = UUID.randomUUID().toString();
		Request request = new Request();
		request.orderCode = orderCode;
		request.serialNo = serialNo;

		CompletableFuture<Map<String, Object>> future = new CompletableFuture<>();
		request.future = future;
		queue.add(request);
		//调用远程接口
		//return remoteServiceCall.queryOrderInfoByCode(orderCode);//调订单系统提供的订单接口 dubbo http
		return future.get();//不断监听自己的线程有没有返回值： 阻塞
	}

	@PostConstruct
	public void init(){
		ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
		scheduled.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // todo
                int size = queue.size();
                if (size == 0) {
                    return;
                }

                List<Map<String,String>> params = new ArrayList<>();
                ArrayList<Request> requests = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    Request request = queue.poll();
                    Map <String, String> map = new HashMap<>();
                    map.put("ordercode", request.orderCode);
                    map.put("seriaNo", request.serialNo);
                    params.add(map);

                    requests.add(request);
                }
                System.out.println("批量处理的数据量：" + size);

                List<Map<String, Object>> responses = remoteServiceCall.queryOrderInfoByCodeBatch(params);
                for (Request request : requests) {
                    String serialNo = request.serialNo;
                    for (Map<String, Object> response : responses) {
                        String responseSerialNo = (String) response.get("serialNo");
                        if (serialNo.equals(responseSerialNo)) {
                            request.future.complete(response);
                        }
                    }
                }
            }
            //作业：填写业务代码
		},0,10,TimeUnit.MILLISECONDS);
	}
}
